import { AMessage,plugin } from "../../api";
import fetch from 'node-fetch';
import http from 'http'
import https from 'https'
import axios from 'axios'
export class site extends plugin {
    constructor() {
      super({
        name: 'site',
        dsc: '网站模块',
        event: 'message',
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)?cdn.*/,
            fnc: 'cdn',
          },
          {
            reg: /^(#|\/)?备案.*/,
            fnc: 'beian',
          },
         {
            reg: /^(#|\/)?收录.*/,
            fnc: 'shoulu',
          }, 
          {
            reg: /^(#|\/)?ping.*/,
            fnc: 'pingweb',
          },
          {
            reg: /^(#|\/)?测速.*/,
            fnc: 'suweb',
          },
        ],
      });
    }
    async cdn(e: AMessage) {
        const usr_qq = e.user_id;
        const didian = e.msg.replace(/(\/|#)?cdn/, "").trim();
        await this.testCDNUsage(e, usr_qq, didian);
        }
        
        async testCDNUsage(e: AMessage, usr_qq: string, url: string) {
        try {
        const options = {
          method: 'HEAD',
          headers: {
          'User-Agent': 'Mozilla/5.0',
          },
        };
        
        const response: http.IncomingMessage = await new Promise((resolve, reject) => {
            const protocol = url.startsWith('https://') ? https : http;
            const req = protocol.request(url, options, resolve);
            req.on('error', reject);
            req.end();
          });
        
          if (response.headers['x-cache'] || response.headers?.server?.includes('CDN')) {
            console.log(`网站 ${url} 使用了 CDN`);
            e.reply([e.segment.at(usr_qq), `网站使用了 CDN`]);
          } else {
            console.log(`网站 ${url} 没有使用 CDN`);
            e.reply([e.segment.at(usr_qq), `网站没有使用 CDN`]);
          }
        } catch (error) {
          console.error('发生错误：', error);
          e.reply('发生错误');
        }
        }
        
        async beian(e: AMessage) {
            const usr_qq = e.user_id;
            const didian = e.msg.replace(/(\/|#)?备案/, "").trim();
            await this.checkWebsiteFilingStatus(e, usr_qq, didian);
        }
              
        async checkWebsiteFilingStatus(e: AMessage, usr_qq: string, domain: string) {
            try {
                const apiUrl = `https://www.mxnzp.com/api/beian/search?domain=${encodeURIComponent(domain)}`;
            
                const response = await fetch(apiUrl);
                const data = await response.json();
            
                if (data.code === 1 && data.data) {
                  const filingStatus = data.data.status;
                  console.log(`网站 ${domain} 备案状态：${filingStatus}`);
                  e.reply([e.segment.at(usr_qq), `网站备案状态：${filingStatus}`]);
                 } else {
                  console.log(`无法获取网站 ${domain} 的备案信息`);
                   e.reply([e.segment.at(usr_qq), `无法获取网站的备案信息`]);
                 }
            } catch (error) {
              console.error('发生错误：', error);
               e.reply('发生错误');
            }
            }
        
        async suweb(e: AMessage) {
        const startTime = Date.now();
        const usr_qq = e.user_id;
        const didian = e.msg.replace(/(\/|#)?测速/, "").trim();
        try {
        const protocol = didian.startsWith('https') ? https : http;
        await new Promise((resolve, reject) => {
        protocol.get(didian, (res) => {
        res.on('data', () => {});
        res.on('end', resolve);
        }).on('error', reject);
        });
        
          const endTime = Date.now();
          const responseTime = endTime - startTime;
        
          console.log(`网站的响应时间为：${responseTime}ms`);
          e.reply([e.segment.at(usr_qq), `网站的响应时间为：${responseTime}ms`]);
        } catch (error) {
          console.error('发生错误：', error);
          e.reply('发生错误');
        }
        }
        
        async pingweb(e: AMessage) {
        const usr_qq = e.user_id;
        const didian = e.msg.replace(/(\/|#)?ping/, "").trim();
        
        const startTime = Date.now();
        
        try {
          const response = await fetch(didian);
          const endTime = Date.now();
          const elapsedTime = endTime - startTime;
        
          e.reply([e.segment.at(usr_qq), `Ping成功，网站访问耗时：${elapsedTime}ms`]);
        } catch (error) {
          console.error('发生错误：', error);
          e.reply('Ping失败');
        }
        }
        
        async shoulu(e: AMessage) {
          const usr_qq = e.user_id;
          const didian = e.msg.replace(/(\/|#)?收录/, "").trim();
          const searchEngines = ['谷歌', '必应', '百度', '搜狗'];
          const results: Promise<{ [engine: string]: number | null; }[]>[] = searchEngines.map(engine => this.querySiteIndex(engine, didian));
          const resolvedResults = await Promise.all(results);
          let message = `网站的收录情况如下：`;
          for (const i in searchEngines) {
            const engine = searchEngines[i];
            const count = resolvedResults[i];
            message += `
        ${engine}:`;
            if (count === null) {
              message += `无法响应`;
            } else {
              message += `${count}条`;
            }
          }
          console.log([usr_qq, `${message}`]);
          e.reply([e.segment.at(usr_qq), `${message}`]);
          }
          
          async querySiteIndex(engine: string, domain: string): Promise<{ [engine: string]: number | null; }[]> {
            let searchUrl = '';
            switch (engine) {
              case '谷歌':
                searchUrl = `https://www.google.com/search?q=site:${domain}`;
                break;
              case '必应':
                searchUrl = `https://www.bing.com/search?q=site:${domain}`;
                break;
              case '百度':
                searchUrl = `https://www.baidu.com/s?wd=site:${domain}`;
                break;
              case '搜狗':
                searchUrl = `https://www.sogou.com/web?query=site:${domain}`;
                break;
              default:
                return [{ [engine]: null }];
            }
          
            try {
              const response = await fetch(searchUrl);
              const html = await response.text();
              const count = this.parseCountFromHtml(engine, html);
              return [{ [engine]: count }];
            } catch (error) {
              console.error(`查询${engine}收录数量时出错：`, error);
              return [{ [engine]: null }];
            }
          }
          
          parseCountFromHtml(engine:string,html:string): number | null {
            let count:number | null = null;
            switch (engine) {
              case '谷歌':
                const googleRegex = /找到约([\d,.]+)个结果/i;
                const googleMatch = html.match(googleRegex);
                if (googleMatch && googleMatch[1]) {
                  count = parseInt(googleMatch[1].replace(/[,|.]/g, ''));
                }
                break;
              case '必应':
                const bingRegex = /共([\d,.]+)条结果/i;
                const bingMatch = html.match(bingRegex);
                if (bingMatch && bingMatch[1]) {
                  count = parseInt(bingMatch[1].replace(/[,|.]/g, ''));
                }
                break;
              case '百度':
                const baiduRegex = /找到相关结果([\d,.]+)个/i;
                const baiduMatch = html.match(baiduRegex);
                if (baiduMatch && baiduMatch[1]) {
                  count = parseInt(baiduMatch[1].replace(/[,|.]/g, ''));
                }
                break;
              case '搜狗':
                const sogouRegex = /找到约([\d,.]+)条结果/i;
                const sogouMatch = html.match(sogouRegex);
                if (sogouMatch && sogouMatch[1]) {
                  count = parseInt(sogouMatch[1].replace(/[,|.]/g, ''));
                }
                break;
              default:
                count = 0;
            }
            return count;
          }
}
